import 'dart:async';

extension ThrottleExtension on Function {
  void Function() throttle([int milliseconds = 1500]) {
    bool _isAllowed = true;
    Timer? _throttleTimer;
    return () {
      if (!_isAllowed) return;
      _isAllowed = false;
      this();
      _throttleTimer?.cancel();
      _throttleTimer = Timer(Duration(milliseconds: milliseconds), () {
        _isAllowed = true;
      });
    };
  }
}
// extension DebounceExtension on Function {
//   void Function() debounce([int milliseconds = 500]) {
//     Timer? _debounceTimer;
//     return () {
//       if (_debounceTimer?.isActive ?? false) _debounceTimer?.cancel();
//       _debounceTimer = Timer(Duration(milliseconds: milliseconds), (){});
//     };
//   }
// }

/// 函数防抖
///
/// [func]: 要执行的方法
/// [delay]: 要迟延的时长
Function bottomDebounce(
    Function? func, [
      Duration delay = const Duration(milliseconds: 2000),
    ]) {
  Timer? timer;
  Function target = () {
    if (timer?.isActive ?? false) {
      timer?.cancel();
    }
    timer = Timer(delay, () {
      func?.call();
    });
  };
  return target;
}

class ButtonUtil {
  /*防止重复点击方法*/
  static debounce(Function fn, {int t = 1500}) {
    int timeOld = 0;
    return () {
      int timeNew = DateTime.timestamp().millisecondsSinceEpoch;
      if (timeNew - timeOld < t) {return;}
      fn();
      timeOld = timeNew;
    };
  }
}